from datetime import datetime


class TypeMismatchException(Exception):
    """
    类型不匹配异常
    """

    def __init__(
        self,
        expected_type: str | tuple,
        actual_type: str,
        context: str = None,
        extra_info: str = None,
    ):
        """
        :param expected_type: 期望的类型（可接受类型元组）
        :param actual_type: 实际传入的类型
        :param context: 类型校验上下文（如字段名称）
        :param extra_info: 额外补充信息
        """
        self.expected_type = expected_type
        self.actual_type = actual_type
        self.context = context
        self.extra_info = extra_info
        self.timestamp = str(datetime.now())

        # 构建错误信息
        message = f"类型不匹配: 期望 {self._format_type(expected_type)}"
        message += f", 但实际是 {actual_type}"

        if context:
            message = f"[{context}] {message}"
        if extra_info:
            message += f" ({extra_info})"

        super().__init__(message)

    @staticmethod
    def _format_type(tp) -> str:
        """格式化类型显示"""
        if isinstance(tp, tuple):
            return "或".join(str(t) for t in tp)
        return str(tp)
